package com.doform.android.xianggucheng.activity.library;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.bean.ArticleQueryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListArticleBean2;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-24.
 * GitHub：https://github.com/cxydxpx
 */

public class ListArticlaActivity2 extends BaseTitleActivity implements OnRefreshListener, OnLoadmoreListener {

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_empty)
    TextView mEmpty;

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;

    @BindView(R.id.et_query)
    EditText et_query;

    @BindView(R.id.rl1)
    RelativeLayout rl1;
    private CommonAdapter mCommonAdapter;
    private List<ArticleQueryBean> mDatas = new ArrayList<>();

    @Override
    protected int layoutResId() {
        return R.layout.activity_article_manager;
    }

    @Override
    protected void initView() {
        super.initView();

        rl1.setVisibility(View.GONE);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("搜索商品");
    }

    @Override
    protected void initData() {
        super.initData();
        refresh();
    }

    private void refresh() {
        getDataForService();
    }

    @Override
    protected void initListener() {
        super.initListener();
        initAdapter();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setEnableHeaderTranslationContent(false);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        getDataForService2();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        getDataForService2();
    }

    private void initAdapter() {

        mCommonAdapter = new CommonAdapter<ArticleQueryBean>(this, R.layout.activity_article_manager_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final ArticleQueryBean articleBean, final int position) {

                TextView tv_name = holder.getView(R.id.tv_name);
                TextView tv_shops_name = holder.getView(R.id.tv_shops_name);
                TextView tv_inventory = holder.getView(R.id.tv_inventory);
                final TextView tv_cost = holder.getView(R.id.tv_cost);
                TextView tv_classify_name = holder.getView(R.id.tv_classify_name);
                ImageView ivIsUploadedPicture = holder.getView(R.id.iv_isUploadedPicture);

                if (TextUtils.isEmpty(articleBean.getImg())) {
                    ivIsUploadedPicture.setVisibility(View.INVISIBLE);
                } else {
                    ivIsUploadedPicture.setVisibility(View.VISIBLE);
                }
                tv_name.setText(articleBean.getName());
                tv_shops_name.setText(articleBean.getSuppliername());
                tv_classify_name.setText("分类：" + articleBean.getClslayernames());
                tv_inventory.setText(articleBean.getKunum());
                tv_cost.setText(articleBean.getBuyprice_det());
            }
        };

        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent();
                intent.putExtra(Constans.EXTRA_ADD_LIBRARY_SEARCH_GOODS, mDatas.get(position));
                setResult(Constans.REQYEST_ADD_LIBRARY_ADD_GOODS, intent);
                finish();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    /**
     *
     */
    private void getDataForService() {
        HttpManager.instance()
                .getArtiQueryByVendorId(new ReqListArticleBean2())
                .compose(new DialogTransformer<ArrayList<ArticleQueryBean>>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<ArrayList<ArticleQueryBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<ArticleQueryBean> articleQueryBeen) {
                        parseData(articleQueryBeen);
                    }
                });
    }

    private void getDataForService2() {
        HttpManager.instance()
                .getArtiQueryByVendorId(new ReqListArticleBean2())
                .subscribe(new ErrorHandleSubscriber<ArrayList<ArticleQueryBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<ArticleQueryBean> articleQueryBeen) {
                        parseData(articleQueryBeen);
                    }
                });
    }


    private void parseData(List<ArticleQueryBean> data) {//解析从服务器获取的数据
        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (data.size() == 0 || data == null) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }
        mDatas.addAll(data);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    @OnClick({R.id.btn_query})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_query:
                String mQuery = et_query.getText().toString().trim();
                if (TextUtils.isEmpty(mQuery)) {
                    refresh();
                    return;
                }
                mCurrentPage = PAGE_CONTENT_INIT;
                getDataForService();
                break;
            default:
                break;
        }
    }


}
